<template>
  <!-- 余额支付弹窗 -->
  <el-dialog v-model="dialogVisible" title="订单支付" width="500">
    <el-input v-model="password" style="width: 240px" type="password" placeholder="请输入密码" show-password />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="payBalance">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 支付宝/微信支付弹窗 -->
  <el-dialog
  v-model="qrCodeDialogVisible"
  title="扫码支付"
  width="500"
  >
    <div class="qr-code">
      <img :src="payChannel === 'alipay'
        ? defaultAlipayQR
        : defaultWechatQR" alt="QR Code" />
      <p>请使用{{ payChannel }}扫描二维码完成支付</p>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="qrCodeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="qrCodeDialogVisible = false">已完成支付</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { getOrderAPI, payAPI } from "@/apis/pay";
import alipayQRImage from '@/assets/images/alipay-qrcode.png';
import wechatQRImage from '@/assets/images/wechat-qrcode.png';

// 获取路由对象
const router = useRouter();

// 弹窗状态
const dialogVisible = ref(false);
const qrCodeDialogVisible = ref(false);

// 支付相关数据
const payChannel = ref("");
const password = ref("");
const orderId = ref("");
const orderInfo = ref({});

// 默认二维码
const defaultAlipayQR = ref(alipayQRImage);
const defaultWechatQR = ref(wechatQRImage);

// 余额支付
const payBalance = async () => {
  const res = await payAPI(orderId.value, password.value);
  if (res.code === 1) {
    dialogVisible.value = false;
    router.push({
      path: "/pay/result",
      query: {
        payResult: 1,
        payChannel: payChannel.value,
        payMoney: orderInfo.value.payMoney,
      },
    });
  }
};

// 支付方法
const pay = async (id, channel) => {
  orderId.value = id;
  payChannel.value = channel;

  const res = await getOrderAPI(id);
  orderInfo.value = res.data;
  if (orderInfo.value.payResult === 0) {
    router.push({
      path: "/pay/result",
      query: {
        payResult: 0,
        payChannel: payChannel.value,
        payMoney: orderInfo.value.payMoney,
      },
    });
  }
  
  if (channel === "余额支付") {
    dialogVisible.value = true;
  } else {
    qrCodeDialogVisible.value = true;
  }
};

// 暴露方法
defineExpose({
  pay,
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.qr-code {
  text-align: center;
}

.qr-code img {
  width: 200px;
  height: 200px;
}

.qr-code p {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}
</style>